import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedstate from 'vuex-persistedstate'
Vue.use(Vuex)
import user from './modules/user'
import cart from './modules/cart'


export default new Vuex.Store({
  state: {
    list: [],
    userInfo: {}
  },
  getters: {
    totalPrice: state => {
      let total = 0
      state.list.filter(item => {
        return item.isSelect
      }).forEach(item => {
        total += item.price * item.count
      })
      return total
    }
  },
  mutations: {
    removeById(state, id) {
      console.log(id);
      state.list = state.list.filter(item => {
        return item.id !== id
      })
    },
    initList(state, data) {
      state.list = data
    },
    changeSelect(state, item) {
      item.isSelect != item.isSelect
    },
    selectAll(state) {
      state.list.forEach(item => {
        item.isSelect = true
      })
    },
    selectCancle(state) {
      state.list.forEach(item => {
        item.isSelect = false
      })
    }
  },
  actions: {
    initListData(context, data) {
      context.commit('initList', data)
    }
  },
  modules: {
    user,
    cart
  },
  plugins: [
    createPersistedstate({
      storage: window.sessionStorage,
      reducer(val) {
        return {
          // 只储存state中的token，而不会缓存uid
          list: val.list
        }
      }
    })
  ]

})